package com.alibaba.basic.util;

import com.alibaba.basic.jwt.JwtUtils;
import com.alibaba.basic.jwt.LoginData;
import com.alibaba.basic.jwt.Payload;
import com.alibaba.basic.jwt.RsaUtils;
import com.alibaba.user.domain.Logininfo;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;

import java.security.PublicKey;

/**
 * 获取当前登录人的信息
 */
public class LoginContext {
    public static Logininfo getLogininfo(HttpServletRequest request){
        try {
            // 从请求头中获取token
            String token = request.getHeader("token");
            if (token !=null){// 表示已经登录过，有当前信息
                // 获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(LoginContext.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                // 通过公钥解密
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                // 返回
                return   payload.getLoginData().getLogininfo();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


}
